// parser.ts
import type { Remark } from "@/common/type/parser"

const POSITION_MAP = ["middle", "top", "bottom", "frame"] as const

export function parseRemarks(input: string): Remark[] {
  const remarkRegex = /<ID=(\d+)\|(.*?)>/g
  const remarks: Remark[] = []
  let match

  // eslint-disable-next-line no-cond-assign
  while ((match = remarkRegex.exec(input)) !== null) {
    // eslint-disable-next-line unused-imports/no-unused-vars
    const [full, idStr, content] = match
    const id = Number.parseInt(idStr, 10)

    // 处理横线类型
    if (content.startsWith("-")) {
      const [_, positionPart] = content.split("&")
      const position = Number.parseInt(positionPart || "0", 10)
      remarks.push({
        id,
        type: "line",
        position: POSITION_MAP[position] || "middle",
        mobileX: 0,
        mobileY: 0,
        pcX: 0,
        pcY: 0
      })
      continue
    }

    // 解析通用参数
    const [mainPart, positionPart] = content.split("&")
    const position = Number.parseInt(positionPart || "0", 10)
    const [typePart, coordsPart] = mainPart.split("#")

    // 解析坐标
    const [mobileCoords, pcCoords] = coordsPart.split("|").map((coord) => {
      const [x, y, scaleX, scaleY] = coord.split("#").map(Number)
      return { x, y, scaleX, scaleY }
    })

    // 处理不同类型
    if (typePart.startsWith("TXT:")) {
      const [textPart, colorPart] = typePart.split("/FCOLOR=")
      const content = textPart.replace("TXT:", "")
      const colorValue = Number.parseInt(colorPart || "255", 10)
      remarks.push({
        id,
        type: "text",
        content,
        color: `rgb(${colorValue},${colorValue},${colorValue})`,
        position: POSITION_MAP[position] || "middle",
        mobileX: mobileCoords.x,
        mobileY: mobileCoords.y,
        pcX: pcCoords?.x || mobileCoords.x,
        pcY: pcCoords?.y || mobileCoords.y
      })
    } else if (typePart.startsWith("IMG:")) {
      const src = typePart.replace("IMG:", "")
      remarks.push({
        id,
        type: "image",
        src,
        position: POSITION_MAP[position] || "middle",
        mobileX: mobileCoords.x,
        mobileY: mobileCoords.y,
        pcX: pcCoords?.x || mobileCoords.x,
        pcY: pcCoords?.y || mobileCoords.y
      })
    } else if (typePart.startsWith("TEXIAO:")) {
      const [effectId, ...params] = typePart.replace("TEXIAO:", "").split("#")
      remarks.push({
        id,
        type: "effect",
        effectId: Number.parseInt(effectId, 10),
        position: POSITION_MAP[position] || "middle",
        mobileX: mobileCoords.x,
        mobileY: mobileCoords.y,
        pcX: pcCoords?.x || mobileCoords.x,
        pcY: pcCoords?.y || mobileCoords.y,
        width: params.length > 0 ? Number.parseInt(params[0], 10) : 0,
        height: params.length > 1 ? Number.parseInt(params[1], 10) : 0,
        scaleX: mobileCoords.scaleX,
        scaleY: mobileCoords.scaleY
      })
    }
  }

  return remarks
}
